package com.wjf.accesscontrol.util

import android.os.Environment
import android.text.TextUtils
import com.wjf.accesscontrol.MyApplication
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.text.ParseException

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2023/11/14 9:52
 *
 */
/**
 * -1: 其他情况
 * 0: 内部存储
 * 1: 外部存储私有目录
 * 2: 外部存储共享空间
 */
const val FILE_TYPE_1_N = -1
const val FILE_TYPE_0 = 0
const val FILE_TYPE_1 = 1
const val FILE_TYPE_2 = 2

/**
 * delete ： 删除文件和空文件夹，文件夹不为空时，删除失败
 * deleteRecursively：递归删除，即使返回失败，也可能已经删除部分文件
 */
class FileUtils {


    companion object{
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { FileUtils() }
    }
    /**
     * txt -> 写入字符串
     * Android 11及以上不能在根目录下创建文件夹
     */
    fun writeStr2Txt(content: String, folderName: String = "Test", fileName:String = "fileName.txt", fileType: Int = FILE_TYPE_1){

        val folderPath = getFolderPath(folderName = folderName,fileType = fileType, EnvironmentType = Environment.DIRECTORY_DOCUMENTS)
        if (folderExistOrCreate(folderPath)){
            ThreadPoolUtils.instance.cachedThreadPool().execute {
                val file = File(folderPath,fileName)
                if (!file.exists()) { file.createNewFile() }
                //追加模式
                val filerWriter = FileWriter(file, true)
                val bufWriter = BufferedWriter(filerWriter)
                bufWriter.write(content)
                bufWriter.newLine()
                bufWriter.close()
                filerWriter.close()
            }
        }

    }


    /**
     * 检测文件夹，不存在则创建文件夹
     */
    fun folderExistOrCreate(folderPath: String): Boolean {
        if (TextUtils.isEmpty(folderPath)) return false
        //传入指定的路径，然后判断路径是否存在
        val folder = File(folderPath)
        return if (folder.exists()) {
            true
        } else {
            //创建文件夹
            folder.mkdirs()
        }
    }

    /**
     * 获取文件路径
     */
    fun getFolderPath(folderName: String = "Test", fileType: Int = FILE_TYPE_1, EnvironmentType: String = Environment.DIRECTORY_PICTURES): String{

        return when(fileType){
            FILE_TYPE_0 -> {
                "${MyApplication.instance.filesDir.absolutePath}/${folderName}"
            }
            FILE_TYPE_1 -> {
                "${MyApplication.instance.getExternalFilesDir(null)?.absolutePath}/${folderName}"

            }
            FILE_TYPE_2 -> {
                "${Environment.getExternalStoragePublicDirectory(EnvironmentType).absolutePath}/${folderName}"
            }

            else ->{
                folderName
            }
        }
    }

    /**
     * 删除七天之前的日志文件
     */
    fun deleteFileBeforeSevenDays() {
        val folderPath = getFolderPath(folderName = folderName, EnvironmentType = Environment.DIRECTORY_DOCUMENTS)

        val file1: File = File(folderPath)
        val files = file1.listFiles() // 读取
        if (files != null) { // 先判断目录是否为空，否则会报空指针
            for (file in files) {
                val fileName = file.name
                if (fileName.endsWith(".txt")) {
                    try {
                        val s = fileName.substring(0, fileName.lastIndexOf("."))
                        if (AppUtils.daysBetween(s.trim(), TimeUtils.instance.getTime(pattern = "yyyy-MM-dd")) >= 7) {
                            file.delete()
                        }
                    } catch (e: ParseException) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }


}